package com.youfang.sixthmedia.controller;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.client.HttpClient;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.util.EntityUtils;

import com.gzit.store.StoreManager;
import com.gzit.utils.AndroidUtils;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.message.AdvertisementRequest;
import com.youfang.sixthmedia.message.AdvertisementResponse;
import com.youfang.sixthmedia.message.model.Advertisment;
import com.youfang.sixthmedia.net.HttpRemoter;

public class AdController {

	public static String TAG = "AdController";

	public static final String AD_ACTION = "com.sixmedia.ad.action";

	public static final long interval = 5 * 60 * 1000;
	private boolean running;

	AdTask downloader;

	// ////////////////////////////////////////////
	// 确保广告路径的存在
	public static final String AD_PATH = YoufangContext.APP_DIR + "ad" + File.separator;
	static {
		ensurePath();
	}

	private static void ensurePath() {
		File file = new File(AD_PATH);
		if (!file.exists()) {
			file.mkdir();
		}
	}

	// ////////////////////////////////////////////

	// 是否正在执行网络任务...
	private boolean loading;

	class AdTask extends Thread {
		public void run() {

			while (running) {
				loading = true;
				try {
					remoteAD();
				} catch (Exception e) {
					e.printStackTrace();
				}

				loading = false;
				try {
					Thread.sleep(interval);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

		}

	}

	private void remoteAD() {
		AdvertisementResponse resp = new AdvertisementResponse();
		HttpRemoter.doRemote(new AdvertisementRequest(), resp);

		if (!resp.isOk()) {
			Log.i(TAG, "请求广告失败：" + resp.getError());
			return;
		}

		// 广告下载成功
		if (this.downloadAD(resp)) {

			// 1.清理可能存在的旧批次的广告
			StoreManager.deleteByCondition(Advertisment.DUMY, "batchID='"
					+ YoufangContext.getAdBatchID() + "'");

			// 2.保存新批次广告ID
			YoufangContext.setAdBatchID(resp.getBatchID());

			// 3.通知相关的activity显示新的广告
			Intent intent = new Intent();
			intent.setAction(AD_ACTION);
			AndroidUtils.appCtx().sendBroadcast(intent);

		}

	}

	private boolean downloadAD(AdvertisementResponse resp) {

		// 开始下载广告...
		List<Advertisment> ads = resp.getAds();
		boolean ok = false;
		for (Advertisment ad : ads) {
			if (_download(ad)) {
				ok = true;
			}
		}

		return ok;

	}

	private boolean _download(Advertisment ad) {

		HttpClient client = HttpRemoter.getYoufangRemoter().getHttpClient();
		try {

			URI logoURI = new URI(ad.advertisementimg);
			HttpGet get = new HttpGet(logoURI);
			HttpResponse httpResp = client.execute(get);
			int statusCode = httpResp.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				Log.d(TAG, " download failed!statuscode:" + statusCode + ":"
						+ ad.advertisementimg);
				return false;
			}

			byte[] resultBytes = EntityUtils.toByteArray(httpResp.getEntity());

			// 存储到磁盘上...
			if (!storeAD(ad, resultBytes)) {
				return false;
			}

			Log.d(TAG, " download ok:" + ad.advertisementimg);

		} catch (Exception e) {
			e.printStackTrace();
			Log.d(TAG, " download failed:" + ad.advertisementimg + "message:"
					+ e.getMessage());

			return false;

		}

		return true;

	}

	/**
	 * 从本地加载广告列表
	 * 
	 * @return
	 */
	public List<Advertisment> localAD() {
		List<Advertisment> ads = new ArrayList<Advertisment>();
		try {
			String adBatchID = YoufangContext.getAdBatchID();
			List<Advertisment> all = StoreManager.findByConditions(
					Advertisment.DUMY, "batchID=?", new String[] { adBatchID });
			for (Advertisment ad : all) {
				Bitmap bitmap = loadAdBitmap(ad);
				if (bitmap != null) {
					ad.setAdImage(bitmap);
					ads.add(ad);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return ads;

	}

	// 将ad对象转化为图片
	public static Bitmap loadAdBitmap(Advertisment ad) {
		return BitmapFactory.decodeFile(AD_PATH + ad.advertisementid);

	}

	// 存储广告数据
	private boolean storeAD(Advertisment ad, byte[] data) {

		try {
			FileUtils.writeByteArrayToFile(new File(AD_PATH
					+ ad.advertisementid), data);
			ad.store();
		} catch (Exception e) {
			Log.d(TAG,
					" stroed failed:" + ad.advertisementimg + "message:"
							+ e.getMessage());
			return false;
		}

		return true;

	}

	public boolean isLoading() {
		return loading;
	}

	public void setLoading(boolean loading) {
		this.loading = loading;
	}

	public synchronized void start() {
		if (this.running) {
			return;
		}

		this.running = true;
		downloader = new AdTask();
		downloader.start();

	}

}
